#include "selfinfowidget.h"

#include "model/datacenter.h"
#include "debug.h"
#include "toast.h"
#include <QCursor>
#include <QFileDialog>
#include <QTimer>
#include <QGridLayout>
using namespace model;
SelfInfoWidget::SelfInfoWidget(QWidget* parent)
    :QDialog(parent)
{
    //1. 设置整个窗口的属性
    this->setFixedSize(500, 250);
    this->setWindowTitle("个人头像");
    this->setWindowIcon(QIcon(":/resource/image/logo.png"));

    //窗口被关闭时 自动销毁对话框对象
    this->setAttribute(Qt::WA_DeleteOnClose);
    //把窗口一动到鼠标当前位置
    this->move(QCursor::pos());

    //2.创建布局管理器
    layout = new QGridLayout();
    layout->setHorizontalSpacing(10);
    layout->setVerticalSpacing(3);
    layout->setContentsMargins(20, 20, 20, 0);
    layout->setAlignment(Qt::AlignTop);
    this->setLayout(layout);

    //3.创建头像
    avatarBtn = new QPushButton();
    avatarBtn->setFixedSize(75, 75);
    avatarBtn->setIconSize(QSize(75, 75));
    //avatarBtn->setIcon(QIcon(":/resource/image/defaultAvatar.png"));
    avatarBtn->setStyleSheet("QPushButton {border: none; background-color: transparent;}");
    layout->addWidget(avatarBtn, 0, 0, 3, 1);

    QString labelStyle = "QLabel {font-size: 14px; font-weight: 800;}";
    QString btnStyle = "QPushButton {border: none; background-color: transparent;}";
    btnStyle += "QPushButton:pressed { background-color: rgb(210, 210, 210); }";
    QString editStyle = "QLineEdit { border: none; border-radius:5px; padding-left:2px; }";

    int height = 30;

    // 4. 添加用户的 id 的显示
    idTag = new QLabel();
    idTag->setFixedSize(50, height);
    idTag->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    idTag->setText("序号");
    idTag->setStyleSheet(labelStyle);

    idLabel = new QLabel();
    idLabel->setFixedHeight(height);
    idLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);

    // 5. 添加用户的名字的显示
    nameTag = new QLabel();
    nameTag->setFixedSize(50, height);
    nameTag->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    nameTag->setText("昵称");
    nameTag->setStyleSheet(labelStyle);

    nameLabel = new QLabel();
    nameLabel->setFixedHeight(height);
    nameLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);

    nameModifyBtn = new QPushButton();
    nameModifyBtn->setFixedSize(70, 25);
    nameModifyBtn->setIconSize(QSize(20, 20));
    nameModifyBtn->setIcon(QIcon(":/resource/image/modify.png"));
    nameModifyBtn->setStyleSheet(btnStyle);

    nameEdit = new QLineEdit();
    nameEdit->setFixedHeight(height);
    nameEdit->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    nameEdit->setStyleSheet(editStyle);
    nameEdit->hide();

    nameSubmitBtn = new QPushButton();
    nameSubmitBtn->setFixedSize(70, 25);
    nameSubmitBtn->setIconSize(QSize(20, 20));
    nameSubmitBtn->setIcon(QIcon(":/resource/image/submit.png"));
    nameSubmitBtn->setStyleSheet(btnStyle);
    nameSubmitBtn->hide();

    // 6. 添加个性签名
    descTag = new QLabel();
    descTag->setFixedSize(50, height);
    descTag->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    descTag->setText("签名");
    descTag->setStyleSheet(labelStyle);

    descLabel = new QLabel();
    descLabel->setFixedHeight(height);
    descLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);

    descModifyBtn = new QPushButton();
    descModifyBtn->setFixedSize(70, 25);
    descModifyBtn->setIconSize(QSize(20, 20));
    descModifyBtn->setIcon(QIcon(":/resource/image/modify.png"));
    descModifyBtn->setStyleSheet(btnStyle);

    descEdit = new QLineEdit();
    descEdit->setFixedHeight(height);
    descEdit->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    descEdit->setStyleSheet(editStyle);
    descEdit->hide();

    descSubmitBtn = new QPushButton();
    descSubmitBtn->setFixedSize(70, 25);
    descSubmitBtn->setIconSize(QSize(20, 20));
    descSubmitBtn->setIcon(QIcon(":/resource/image/submit.png"));
    descSubmitBtn->setStyleSheet(btnStyle);
    descSubmitBtn->hide();

    // 7. 添加电话
    phoneTag = new QLabel();
    phoneTag->setFixedSize(50, height);
    phoneTag->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    phoneTag->setText("电话");
    phoneTag->setStyleSheet(labelStyle);

    phoneLabel = new QLabel();
    phoneLabel->setFixedHeight(height);
    phoneLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);

    phoneModifyBtn = new QPushButton();
    phoneModifyBtn->setFixedSize(70, 25);
    phoneModifyBtn->setIconSize(QSize(20, 20));
    phoneModifyBtn->setIcon(QIcon(":/resource/image/modify.png"));
    phoneModifyBtn->setStyleSheet(btnStyle);

    phoneEdit = new QLineEdit();
    phoneEdit->setFixedHeight(height);
    phoneEdit->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    phoneEdit->setStyleSheet(editStyle);
    phoneEdit->hide();

    phoneSubmitBtn = new QPushButton();
    phoneSubmitBtn->setFixedSize(70, 25);
    phoneSubmitBtn->setIconSize(QSize(20, 20));
    phoneSubmitBtn->setIcon(QIcon(":/resource/image/submit.png"));
    phoneSubmitBtn->setStyleSheet(btnStyle);
    phoneSubmitBtn->hide();

    // 8. 添加验证码
    verifyCodeTag = new QLabel();
    verifyCodeTag->setFixedSize(50, height);
    verifyCodeTag->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    verifyCodeTag->setText("验证码");
    verifyCodeTag->setStyleSheet(labelStyle);
    //verifyCodeTag->hide();

    verifyCodeEdit = new QLineEdit();
    verifyCodeEdit->setFixedHeight(height);
    verifyCodeEdit->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    verifyCodeEdit->setStyleSheet(editStyle);
    //verifyCodeEdit->hide();

    getVerifyCodeBtn = new QPushButton();
    getVerifyCodeBtn->setText("获取验证码");
    getVerifyCodeBtn->setStyleSheet("QPushButton { border: none; background-color: transparent; } QPushButton:pressed { background-color: rgb(231, 231, 231); }");
    getVerifyCodeBtn->setFixedSize(70, height);
    //getVerifyCodeBtn->hide();

    // 9. 添加到布局管理器. 第 0 列被头像占用了. 下列内容都是从第一列开始往后排
    layout->addWidget(idTag, 0, 1, 1, 1);
    layout->addWidget(idLabel, 0, 2);

    layout->addWidget(nameTag, 1, 1);
    layout->addWidget(nameLabel, 1, 2);
    layout->addWidget(nameModifyBtn, 1, 3);

    layout->addWidget(descTag, 2, 1);
    layout->addWidget(descLabel, 2, 2);
    layout->addWidget(descModifyBtn, 2, 3);

    layout->addWidget(phoneTag, 3, 1);
    layout->addWidget(phoneLabel, 3, 2);
    layout->addWidget(phoneModifyBtn, 3, 3);

    // layout->addWidget(verifyCodeTag, 4, 1);
    // layout->addWidget(verifyCodeEdit, 4, 2);
    // layout->addWidget(getVerifyCodeBtn, 4, 3);

#if TEST_UI
    idLabel->setText("1234");
    nameLabel->setText("xiang");
    descLabel->setText("你相哥");
    phoneLabel->setText("1952135411");
#endif

    //10. 链接信号槽
    initSignalSlot();

    //11. 加载数据到页面上
    DataCenter* dataCenter = DataCenter::getInstance();
    UserInfo* myself = dataCenter->getMyself();
    if(myself != nullptr)
    {
        //有数据 直接显示
        idLabel->setText(myself->userID);
        nameLabel->setText(myself->nickname);
        descLabel->setText(myself->description);
        phoneLabel->setText(myself->phone);
        //头像
        if(!myself->avatar.isNull())
        {
            avatarBtn->setIcon(myself->avatar);
        }
    }
}

void SelfInfoWidget::initSignalSlot()
{
    //点击修改按钮时 把 label 隐藏掉 显示出 edit 和 submit 按钮
    connect(nameModifyBtn, &QPushButton::clicked, this, [=](){
        // 把当前的 nameLabel 和 nameModifyBtn 隐藏起来
        nameLabel->hide();
        nameModifyBtn->hide();
        layout->removeWidget(nameLabel); // 布局会持续管理 “隐藏但未移除” 的控件，可能导致界面布局错乱
        layout->removeWidget(nameModifyBtn);
        // 把 nameEdit 和 nameSubmitBtn 显示出来
        nameEdit->show();
        nameSubmitBtn->show();
        layout->addWidget(nameEdit, 1, 2);
        layout->addWidget(nameSubmitBtn, 1, 3);
        // 把输入框的内容进行设置.
        nameEdit->setText(nameLabel->text());
    });
    // 点击修改签名按钮时
    connect(descModifyBtn, &QPushButton::clicked, this, [=]() {
        descLabel->hide();
        descModifyBtn->hide();
        layout->removeWidget(descLabel);
        layout->removeWidget(descModifyBtn);

        descEdit->show();
        descSubmitBtn->show();
        layout->addWidget(descEdit, 2, 2);
        layout->addWidget(descSubmitBtn, 2, 3);

        descEdit->setText(descLabel->text());
    });
    // 点击修改手机号按钮时
    connect(phoneModifyBtn, &QPushButton::clicked, this, [=]() {
        phoneLabel->hide();
        phoneModifyBtn->hide();
        layout->removeWidget(phoneLabel);
        layout->removeWidget(phoneModifyBtn);

        phoneEdit->show();
        phoneSubmitBtn->show();
        layout->addWidget(phoneEdit, 3, 2);
        layout->addWidget(phoneSubmitBtn, 3, 3);

        verifyCodeTag->show();
        verifyCodeEdit->show();
        getVerifyCodeBtn->show();
        layout->addWidget(verifyCodeTag, 4, 1);
        layout->addWidget(verifyCodeEdit, 4, 2);
        layout->addWidget(getVerifyCodeBtn, 4, 3);

        phoneEdit->setText(phoneLabel->text());
    });

    // 点击提交昵称修改按钮时
    connect(nameSubmitBtn, &QPushButton::clicked, this, &SelfInfoWidget::clickNameSubmitBtn);
    // 点击提交签名修改按钮时
    connect(descSubmitBtn, &QPushButton::clicked, this, &SelfInfoWidget::clickDescSubmitBtn);
    // 点击提交手机号修改按钮时
    connect(phoneSubmitBtn, &QPushButton::clicked, this, &SelfInfoWidget::clickPhoneSubmitBtn);
    // 点击获取验证码按钮时
    connect(getVerifyCodeBtn, &QPushButton::clicked, this, &SelfInfoWidget::clickGetVerifyCodeBtn);
    // 点击头像时 触发修改头像
    connect(avatarBtn, &QPushButton::clicked, this, &SelfInfoWidget::clickAvatarBtn);
}

void SelfInfoWidget::clickNameSubmitBtn()
{
    //获取新名字
    QString newName = nameEdit->text().trimmed();
    if(newName.isEmpty())
    {
        //名字不能为空
        return;
    }
    //发起网络请求 修改昵称
    DataCenter* dataCenter = DataCenter::getInstance();
    connect(dataCenter, &DataCenter::changeNicknameDone, this, &SelfInfoWidget::clickNameSubmitBtnDone, Qt::UniqueConnection);
    dataCenter->changeNicknameAsync(newName);
}

void SelfInfoWidget::clickDescSubmitBtn()
{
    //获取新签名
    QString newDesc = descEdit->text().trimmed();
    if(newDesc.isEmpty())
    {
        //签名不能为空
        return;
    }
    //发起网络请求 修改签名
    DataCenter* dataCenter = DataCenter::getInstance();
    connect(dataCenter, &DataCenter::changeDescriptionDone, this, &SelfInfoWidget::clickDescSubmitBtnDone, Qt::UniqueConnection);
    dataCenter->changeDescriptionAsync(newDesc);
}

void SelfInfoWidget::clickPhoneSubmitBtn()
{
    DataCenter* dataCenter = DataCenter::getInstance();
    //如果手机号没变
    if(phoneEdit->text().trimmed() == dataCenter->getMyself()->phone)
    {
        layout->removeWidget(verifyCodeEdit);
        layout->removeWidget(verifyCodeTag);
        layout->removeWidget(getVerifyCodeBtn);
        layout->removeWidget(phoneEdit);
        layout->removeWidget(phoneSubmitBtn);
        verifyCodeEdit->hide();
        verifyCodeTag->hide();
        getVerifyCodeBtn->hide();
        phoneEdit->hide();
        phoneSubmitBtn->hide();

        phoneLabel->setText(dataCenter->getMyself()->phone);
        layout->addWidget(phoneLabel, 3, 2);
        phoneLabel->show();
        layout->addWidget(phoneModifyBtn, 3, 3);
        phoneModifyBtn->show();

        return;
    }
    //1. 先判断验证码是否已经收到
    const QString verifyCodeId = dataCenter->getCurrentVerifyCodeId();
    //LOG() << "修改手机号 点击提交按钮 verifyCodeId: " << verifyCodeId;
    if(verifyCodeId == "")
    {
        Toast::showMessage("未发送验证码或点击过快 稍后重试！");
        return;
    }
    dataCenter->resetVerifyCodeId(""); //重置验证码id 避免重复使用
    //2. 获取用户输入的验证码
    QString userInputCode = verifyCodeEdit->text().trimmed();
    if(userInputCode.isEmpty())
    {
        Toast::showMessage("请输入验证码");
        return;
    }
    verifyCodeEdit->clear();
    //3. 发送请求
    connect(dataCenter, &DataCenter::changePhoneNumberDone, this, &SelfInfoWidget::clickPhoneSubmitBtnDone, Qt::UniqueConnection);
    // LOG() << "修改手机号 发起网络请求 phoneToChange: " << phoneToChange
    //       << " verifyCodeId: " << verifyCodeId
    //       << " userInputCode: " << userInputCode;
    dataCenter->changePhoneNumberAsync(phoneToChange, verifyCodeId, userInputCode);

    //4. 把验证码CD清空
    cooldown = 1;
}

void SelfInfoWidget::clickNameSubmitBtnDone()
{
    //对界面控件进行切换 把 edit 和 submit 隐藏掉 显示出 label 和 modify 按钮
    nameEdit->hide();
    nameSubmitBtn->hide();
    nameLabel->setText(nameEdit->text().trimmed());
    layout->removeWidget(nameEdit);
    layout->removeWidget(nameSubmitBtn);
    layout->addWidget(nameLabel, 1, 2);
    nameLabel->show();
    nameModifyBtn->show();
    layout->addWidget(nameModifyBtn, 1, 3);

}

void SelfInfoWidget::clickDescSubmitBtnDone()
{
    //对界面控件进行切换 把 edit 和 submit 隐藏掉 显示出 label 和 modify 按钮
    descEdit->hide();
    descSubmitBtn->hide();
    descLabel->setText(descEdit->text().trimmed());
    layout->removeWidget(descEdit);
    layout->removeWidget(descSubmitBtn);
    layout->addWidget(descLabel, 2, 2);
    descLabel->show();
    descModifyBtn->show();
    layout->addWidget(descModifyBtn, 2, 3);

}

void SelfInfoWidget::clickPhoneSubmitBtnDone()
{
    //对界面控件进行切换 把label 和 modify 按钮隐藏掉 把 edit 和 submit显示
    layout->removeWidget(verifyCodeEdit);
    layout->removeWidget(verifyCodeTag);
    layout->removeWidget(getVerifyCodeBtn);
    layout->removeWidget(phoneEdit);
    layout->removeWidget(phoneSubmitBtn);
    verifyCodeEdit->hide();
    verifyCodeTag->hide();
    getVerifyCodeBtn->hide();
    phoneEdit->hide();
    phoneSubmitBtn->hide();

    phoneLabel->setText(phoneToChange);
    layout->addWidget(phoneLabel, 3, 2);
    phoneLabel->show();
    layout->addWidget(phoneModifyBtn, 3, 3);
    phoneModifyBtn->show();

}

void SelfInfoWidget::clickGetVerifyCodeBtn()
{
    //1. 获取手机号
    QString phoneNumber = phoneEdit->text().trimmed();
    if(phoneNumber.isEmpty())
    {
        //手机号不能为空
        return;
    }
    DataCenter* dataCenter = DataCenter::getInstance();
    if(phoneNumber == dataCenter->getMyself()->phone)
    {
        Toast::showMessage("新手机号不能和旧手机号相同");
        return;
    }
    //2. 发起网络请求 获取验证码
    connect(dataCenter, &DataCenter::getVerifyCodeDone, this, [=]()
    {
        Toast::showMessage("该应用未通过工信部备案，您无法收到验证码，但手机号已经入数据库保存 详情私聊开发者", 6000);
    });
    dataCenter->getVerifyCodeAsync(phoneNumber);

    //3.把刚才请求的手机号保存起来  保证修改的手机号和验证码的是同一个手机号
    phoneToChange = phoneNumber;

    //4.禁用发送验证码按钮 并给出30s冷却
    getVerifyCodeBtn->setEnabled(false);
    cooldown = 30;
    QTimer* timer = new QTimer(this);
    getVerifyCodeBtn->setText(QString::number(cooldown) + "s后重发");

    connect(timer, &QTimer::timeout, this, [=](){
        cooldown--;
        if (cooldown <= 0) {
            getVerifyCodeBtn->setText("获取验证码");
            getVerifyCodeBtn->setEnabled(true);
            timer->stop();
            timer->deleteLater();
        } else {
            getVerifyCodeBtn->setText(QString::number(cooldown) + "s后重发");
        }
    });
    timer->start(1000); // 每1秒触发一次
}

void SelfInfoWidget::clickAvatarBtn()
{
    //1. 打开文件选择对话框 选择图片
    QString filter = "图片文件 (*.png *.jpg *.jpeg *.bmp)";
    QString filePath = QFileDialog::getOpenFileName(this, "选择头像", QDir::homePath(), filter);
    if(filePath.isEmpty())
    {
        //用户取消选择
        return;
    }
    //2.根据路径 读取到图片内容
    QByteArray imageBytes = loadFileToByteArray(filePath);

    //3.发起网络请求 修改头像
    DataCenter* dataCenter = DataCenter::getInstance();
    dataCenter->changeAvatarAsync(imageBytes);
    connect(dataCenter, &DataCenter::changeAvatarDone, this, &SelfInfoWidget::clickAvatarBtnDone, Qt::UniqueConnection);


}

void SelfInfoWidget::clickAvatarBtnDone()
{
    //把头像显示出来
    DataCenter* dataCenter = DataCenter::getInstance();
    avatarBtn->setIcon(dataCenter->getMyself()->avatar);
}







